from uuid import uuid4

from rest_framework import serializers

from .models import User
from util.exception import ValidationError


class UserSerializer(serializers.ModelSerializer):
    username = serializers.CharField(max_length=20, allow_null=False, allow_blank=False)
    password = serializers.CharField(max_length=20, allow_blank=False, allow_null=False)

    class Meta:
        model = User
        fields = ["id", "username", "password"]

    def validate_username(self, obj):
        user = User.objects.filter(username=obj).first()
        if user:
            raise ValidationError(10001)
        return obj

    def create(self, validated_data):
        User.objects.create(**validated_data)


class UserSerializerList(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ["id", "username", "is_active"]


class UserserializerUpdate(serializers.ModelSerializer):
    id = serializers.CharField(max_length=32, allow_null=False)
    password = serializers.CharField(max_length=20, allow_null=True)
    is_active = serializers.BooleanField(allow_null=True)
    is_delete = serializers.BooleanField(allow_null=True)

    class Meta:
        model = User
        fields = ["id", "password", "is_active", "is_delete"]

    def validate(self, attrs):
        id = attrs.get("id")
        user = User.objects.filter(id=id, is_delete=False).first()
        if not user:
            raise ValidationError(10002)
        new_attrs = {}
        for key, value in attrs.items():
            if value is not None:
                new_attrs[key] = value
        return new_attrs

    def update(self, data):
        User.objects.filter(id=data["id"]).update(**data)
